#!/usr/bin/python
# -*- coding: iso-8859-15 -*-
#|*************************************************************|
#|* Crazy Beaver - Automatic NZB downloader upon IMDB filter   |
#|*************************************************************|
#|                                                             |
#|                                                             |
#|                             GUI Created by Gotcha007 - 2011 |
#|*************************************************************|
#|*************************************************************|

import urllib
import httplib
import xml.dom.minidom
import re
import string
import json
import datetime
import sqlite3 as sqlite
import wx.animate
import wx
import sys
from threading import Thread
from checkmovie import CheckMovie
from string import printable as _printableChars
from cStringIO import StringIO
from threading import Event, Thread
import time
import subprocess
import os
import mechanize
import socket
import webbrowser
from configobj import ConfigObj
from datetime import date, timedelta

config = ConfigObj('./config.ini') 

#execfile("./config.ini")
ID_DELETE = 4 #Id used for the Delete Button

Version = "0.5.2b"

class MainWindow(wx.Frame):
     def __init__(self,titre):

          #------Creation of the Main Frame------ 
          wx.Frame.__init__(self, None, 1, title = titre, size = (1115, 800))
          self.SetBackgroundColour("white")

          self.panel = wx.Panel(self,size=(1100,800))
          self.panel.SetBackgroundColour("white")
     
          # Create the InfoBar.  It starts out in a hidden state so it
          # won't be visible until we need it.
          self.info = wx.InfoBar(self.panel)
          self.messageWarning = wx.TextCtrl(self.panel, -1, "Last Movie Check has Generated some Warning, please have a look at the Warning Log", size=(250,-1))
          self.messageWarning.Hide()
          self.messageError = wx.TextCtrl(self.panel, -1, "Last Movie Check has Generated en Error, please have a look at the Error Log", size=(250,-1))
          self.messageError.Hide()
    
          #------End of Creation of the Main Frame------ 
          
          #------Creation of Listcrt + Event associated to it------          
          self.panel.list = wx.ListCtrl(self.panel, 99,pos=(5,120), size=(510,480),style=wx.LC_REPORT|wx.SUNKEN_BORDER|wx.LC_HRULES)
          self.Bind(wx.EVT_LIST_ITEM_SELECTED,self.OnSelect,self.panel.list)
          self.Bind(wx.EVT_LIST_KEY_DOWN, self.ListEvtKeyDown, self.panel.list) 
          #------End of Creation of Listcrt + Event associated to it------          
          
          #------Creation of Column for Listcrt------
          
          self.panel.list.InsertColumn(0,"Movie NZB")
          self.panel.list.SetColumnWidth(0, 320)
          self.panel.list.InsertColumn(1,"Indexer")
          self.panel.list.SetColumnWidth(1, 65)
          self.panel.list.InsertColumn(2,"Date")
          self.panel.list.SetColumnWidth(2, 100)
          self.panel.list.InsertColumn(3,"Id")
          self.panel.list.SetColumnWidth(3, 1)
          #------End of Creation of Column for Listcrt------
          
          #------Load icons------
          il = wx.ImageList(30,30, True)
          bmp = wx.Bitmap("./images/Icon01big.jpg", wx.BITMAP_TYPE_JPEG)
          self.il_max = il.Add(bmp)
          bmp = wx.Bitmap("./images/Icon02big.jpg", wx.BITMAP_TYPE_JPEG)
          self.il_maxGood = il.Add(bmp)
          bmp = wx.Bitmap("./images/couchpotato.png", wx.BITMAP_TYPE_PNG)
          self.il_maxCouch = il.Add(bmp)
          bmp = wx.Bitmap("./images/xbmc.png", wx.BITMAP_TYPE_PNG)
          self.il_maxXbmc = il.Add(bmp)
          #bmp = wx.Bitmap("./images/nzbmatrixsmall.png", wx.BITMAP_TYPE_PNG)
          #self.il_maxnzbmatrix = il.Add(bmp)
          bmp = wx.Bitmap("./images/couchpotatosnatched.png", wx.BITMAP_TYPE_PNG)
          self.il_maxCouchSnatched = il.Add(bmp)
          bmp = wx.Bitmap("./images/newok.png", wx.BITMAP_TYPE_PNG)
          self.il_maxNewOk = il.Add(bmp)
          bmp = wx.Bitmap("./images/newnok.png", wx.BITMAP_TYPE_PNG)
          self.il_maxNewNOk = il.Add(bmp)
          #------End of Load Icons------
          
          self.panel.list.AssignImageList(il, wx.IMAGE_LIST_SMALL)
          
          #------Opening connection to Histo DB------          
          connHisto = sqlite.connect('./History.db')
          connHisto.row_factory = sqlite.Row
          cHisto = connHisto.cursor()

          d=datetime.datetime.now()-timedelta(days=int(config['history_display_days']))
          cHisto.execute('select * from Movie where date > "' + str(d) + '" ORDER BY date desc')
          #------End of Opening connection to Histo DB------
          
          #------Fill in the ListCtrl------ 
          i = 0
          for row in cHisto:
               img =  self.il_max
               temp = row["Title"]
               temp = temp.replace(",","")
               temp = temp.replace("'","")
               if row["New"] == "yes" :
                    if row["Downloaded"] == "yes" :
                         img =  self.il_maxNewOk
                    else:
                         img =  self.il_maxNewNOk
               else:
                    if row["Downloaded"] == "yes" :
                         img =  self.il_maxGood
                    else :
                         if config['couchpotato_connection'] == "yes":
                              #------Opening connection to CouchPotato DB------          
                              connCouch = sqlite.connect(config['couchpotato_path'] + 'data.db')
                              connCouch.row_factory = sqlite.Row
                              cCouch = connCouch.cursor()
                              cCouch.execute('select name,status from Movie where name="' + row["ImdbTitle"] + '" and (status="want" OR status="snatched")')
                              #------End of Opening connection to CouchPotato DB------
                              
                              for rowCouch in cCouch:
                                   if row["ImdbTitle"] == rowCouch["name"]:
                                        if rowCouch["status"] == "snatched":
                                             img =  self.il_maxCouchSnatched
                                        else:
                                             img =  self.il_maxCouch
                                   else:
                                        img =  self.il_max
                              cCouch.close()
                         if config['xbmc_connection'] == "yes":
                              #------Opening connection to XBMC DB------ 
                              connXbmc = sqlite.connect(config['xbmc_path'] + 'MyVideos34.db')
                              connXbmc.row_factory = sqlite.Row
                              cXbmc = connXbmc.cursor()
                              cXbmc.execute('select c00 from movie where c00="' + row["ImdbTitle"] + '"')
                              #------End of Opening connection to XBMC DB------
                              for rowXbmc in cXbmc:
                                   if row["ImdbTitle"] == rowXbmc["c00"]:
                                        img =  self.il_maxXbmc
                                        
                              cXbmc.close()    
               self.panel.list.InsertImageStringItem(i, temp, img)
               self.panel.list.SetStringItem(i,1,row["Indexer"])
               self.panel.list.SetStringItem(i,2,row["Date"])
               self.panel.list.SetStringItem(i,3,row["Id"])
               i = i + 1
               
          #------End of Fill in the ListCtrl------
          
          cHisto.close() #Closing the connection to the Histo DB
          
          #------Placement of the panel------          
          self.panel.vbox = wx.BoxSizer(wx.VERTICAL)
          self.panel.hbox1 = wx.BoxSizer(wx.HORIZONTAL)
          self.panel.vbox.Add(self.info, 0, wx.TOP|wx.EXPAND,1)
          #self.panel.hbox1.Add(self.panel.list, 1, wx.TOP, 120)
          self.panel.vbox.Add(self.panel.hbox1, 0)          
          self.panel.SetSizer(self.panel.vbox)
          #------End of Placement of the panel------
          
          #------Creation of the server Radio Button------
          #self.panel.ChooseServer = wx.StaticText(self.panel, -1, 'Choose Server', pos = (3,55))
          #font = wx.Font(10,wx.FONTFAMILY_ROMAN,wx.SLANT,wx.NORMAL)
          #self.panel.ChooseServer.SetFont(font)
          self.imageFile = "./images/arrow.png"
          self.jpg1 = wx.Image(self.imageFile, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
          # bitmap upper left corner is in the position tuple (x, y) = (5, 5)
          self.panel.Arrow = wx.StaticBitmap(self, -1, self.jpg1, (160 , 38), (self.jpg1.GetWidth(), self.jpg1.GetHeight()))
          self.panel.server1 = wx.RadioButton ( self.panel, -1, 'nzbmatrix', pos=(220,85),style = wx.RB_GROUP )
          self.panel.server2 = wx.RadioButton ( self.panel, -1, 'nzbs',pos=(300,85) )
          self.panel.server3 = wx.RadioButton ( self.panel, -1, 'nzbsu',pos=(350,85) )
          #------End of Creation of the server Radio Button------
          
          #------Creation of Button + Event associated with it------          
          #self.panel.dlt = wx.Button(self.panel, ID_DELETE, label='Delete Selected', pos=(340, 35))
          #self.panel.dlt.Bind(wx.EVT_BUTTON, self.OnDelete, id=ID_DELETE)
          #self.Bind(wx.EVT_LISTBOX, self.OnSelect, id=26)
          Img = wx.Bitmap("./images/checkmovies.jpg", wx.BITMAP_TYPE_JPEG)
          
          self.panel.CheckMovieBtn = wx.Button(self.panel, id=-1,pos=(5, 64),size=(150,39), style=wx.NO_BORDER)
          self.panel.CheckMovieBtn.Bind(wx.EVT_BUTTON, self.CheckMovieBtnClick)
          self.panel.CheckMovieBtn.SetBitmapLabel(Img)
          
          if config['couchpotato_connection'] == "yes":
               #------Opening connection to CouchPotato DB------          
               connCouch = sqlite.connect(config['couchpotato_path'] + 'data.db')
               connCouch.row_factory = sqlite.Row
               cCouch = connCouch.cursor()   
               cCouch.execute("select name,imdb from Movie where status='want'")
               
               #------Opening connection to Histo DB------          
               connHisto = sqlite.connect('./History.db')
               connHisto.row_factory = sqlite.Row
               cHisto = connHisto.cursor()
     
               i = 0
               for rowCouch in cCouch:
                    cHisto.execute('select Title from Movie where ImdbId = "' + rowCouch["imdb"] +'"')
                    for rowHisto in cHisto:
                         i = i + 1 
                         break
               #------End of Opening connection to CouchPotato DB------
                         
               cCouch.close()
               cHisto.close()

          self.ImgStatus = "./images/couchpotatobig" + str(i) +".png"
          ImgStatusCouch = wx.Bitmap(self.ImgStatus, wx.BITMAP_TYPE_PNG)
          #label=str(i) + " Movie(s) Found in CouchPotato"
          self.panel.MovieCouchBtn = wx.Button(self.panel, id=-1,pos=(445, 55), size=(60,63), style=wx.NO_BORDER)
          self.panel.MovieCouchBtn.Bind(wx.EVT_BUTTON, self.OnCouchCheck)
          self.panel.MovieCouchBtn.SetBitmapLabel(ImgStatusCouch)
          self.panel.MovieCouchBtn.SetToolTip(wx.ToolTip("Click here to show some releases have been found for you movies that you are watching in CouchPotato"))
          
          #------No Movie found that are in Couch Potato so Hiding the Couch Potato image------
          if i == 0:
               self.panel.MovieCouchBtn.Hide()
               
          self.ImgStatus = "./images/Btn1.png"
          ImgStatusCouch = wx.Bitmap(self.ImgStatus, wx.BITMAP_TYPE_PNG)
          self.panel.MovieCouchBtnN = wx.Button(self.panel.MovieCouchBtn, id=-1,pos=(480, 55), size=(30,31), style=wx.NO_BORDER)
          self.panel.MovieCouchBtnN.SetBitmapLabel(ImgStatusCouch)
          
          if i == 0:
               self.panel.MovieCouchBtn.Hide()

          #self.imageLegend1 = './images/Paypal.gif'
          #bmp = wx.Bitmap(self.imageLegend1, wx.BITMAP_TYPE_GIF)
          #self.panel.DonateBtn = wx.Button(self.panel, id=-1,size=(67,31),pos=(5, 522),style=wx.BORDER_NONE)
          #self.panel.DonateBtn.Bind(wx.EVT_BUTTON, self.DonateBtnClick)
          #self.panel.DonateBtn.SetBitmapLabel(bmp)
          
          #------End of Creation of Button + Event associated with it------
          
          #------Creation of the Menu------
          menuOption = wx.Menu()
          menuOption.Append(wx.ID_OPEN, "&Config")
          menuOption.AppendSeparator()
          menuOption.Append(wx.ID_EXIT, "&Quit\tCTRL+q")
          menuBar = wx.MenuBar()
          menuBar.Append(menuOption, "&Options")
          self.SetMenuBar(menuBar)
          wx.EVT_MENU(self, wx.ID_EXIT, self.OnExit)
          menuLogs = wx.Menu()
          menuLogs.Append(50, "&Warning Log")
          menuLogs.Append(51, "&Error Log")
          menuLogs.Append(54, "&Console Log")
          menuLogs.AppendSeparator()
          menuLogs.Append(52, "&Clear Warning Log")
          menuLogs.Append(53, "&Clear Error Log")
          menuLogs.Append(55, "&Clear Console Log")
          wx.EVT_MENU(self, 50, self.OnWarningLog)
          wx.EVT_MENU(self, 51, self.OnErrorLog)
          wx.EVT_MENU(self, 54, self.OnConsoleLog)
          wx.EVT_MENU(self, 52, self.OnClearWarningLog)
          wx.EVT_MENU(self, 53, self.OnClearErrorLog)
          wx.EVT_MENU(self, 55, self.OnClearConsoleLog)
          menuBar.Append(menuLogs, "&Logs")
          #wx.EVT_MENU(self, wx.ID_OPEN, self.OnConfig)
          #------End Creation of the Menu------
          
          #------Creation of the Status Bar + Event assiciated with it------          
          self.bar = wx.StatusBar(self, 1)
          self.bar.SetFieldsCount(2)
          self.bar.SetStatusWidths([170,750])
          self.SetStatusBar(self.bar)
          #------End of Creation of the Status Bar------

          #------Creation of the Animated Gif Loading------
          # pick the filename of an animated GIF file you have ...
          # give it the full path and file name!
          #ag_fname = "./images/loading-gif-animation.gif"
          #self.panel.ag = wx.animate.GIFAnimationCtrl(self, -1, ag_fname, pos=(155, 70))
          # clears the background
          #self.panel.ag.GetPlayer().UseBackgroundColour(True)
          # continuously loop through the frames of the gif file (default)

          # pick the filename of an animated GIF file you have ...
          # give it the full path and file name!
          ag_fname2 = "./images/crazybeaverbanner.jpg"
          self.jpg1 = wx.Image(ag_fname2, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
          # bitmap upper left corner is in the position tuple (x, y) = (5, 5)
          self.panel.Arrow = wx.StaticBitmap(self, -1, self.jpg1, pos=(550, 10), size=(self.jpg1.GetWidth(), self.jpg1.GetHeight()))
          #------End of Creation of the Animated Gif Loading------

          ag_fname2 = "./images/info.jpg"
          self.jpg1 = wx.Image(ag_fname2, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
          # bitmap upper left corner is in the position tuple (x, y) = (5, 5)
          self.panel.Info = wx.StaticBitmap(self, -1, self.jpg1, pos=(520, 120), size=(self.jpg1.GetWidth(), self.jpg1.GetHeight()))

          ag_fname2 = "./images/top.jpg"
          self.jpg1 = wx.Image(ag_fname2, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
          # bitmap upper left corner is in the position tuple (x, y) = (5, 5)
          self.panel.Arrow = wx.StaticBitmap(self, -1, self.jpg1, pos=(1, 1), size=(self.jpg1.GetWidth(), self.jpg1.GetHeight()))

          #------Creation of the Thread------
          self.lt = CheckMovie(self) # We need to give the instance of the main
          #------End of Creation of the Thread------
          
          self.Trun = 0
          
          #|*******************************************************************************************|
          #|Panel Movie Info creation                                                                  |
          #|*******************************************************************************************|
          
          #------------Poster--------------
          # pick a .jpg file you have in the working folder
          
          self.imageFile = './images/NOPOSTER.jpg'
          self.jpg1 = wx.Image(self.imageFile, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
          # bitmap upper left corner is in the position tuple (x, y) = (5, 5)
          self.panel.Poster = wx.StaticBitmap(self, -1, self.jpg1, (420 + self.jpg1.GetWidth(), 193), (self.jpg1.GetWidth(), self.jpg1.GetHeight()))
          self.panel.Poster.Hide()
          
          #------------End of Poster--------------
          
          #------------Title--------------
          #str = "Nothing"
          self.panel.TitleMovie = wx.StaticText(self, -1, '', pos = (730,195))
          self.panel.TitleMovie.SetBackgroundColour("#413f3f")
          self.panel.TitleMovie.SetForegroundColour(wx.WHITE)
          font = wx.Font(12,wx.FONTFAMILY_ROMAN,wx.SLANT,wx.BOLD)
          self.panel.TitleMovie.SetFont(font)

          #------------End of Title--------------
          
          #------------Genres--------------
          #str = "Nothing"
          self.panel.GenreMovie = wx.StaticText(self, -1, '', pos = (730,215))
          font = wx.Font(10,wx.FONTFAMILY_ROMAN,wx.SLANT,wx.NORMAL)
          self.panel.GenreMovie.SetFont(font)
          self.panel.GenreMovie.SetForegroundColour(wx.WHITE)
          self.panel.GenreMovie.SetBackgroundColour("#413f3f")
          #------------End of Genre--------------
          
          #------------Rating--------------
          #str = "Nothing"
          self.panel.RatingMovie = wx.StaticText(self, -1, '', pos = (730,245))
          self.panel.RatingMovieOn = wx.StaticText(self.panel, -1, '', pos = (755,245))
          font = wx.Font(15,wx.FONTFAMILY_ROMAN,wx.SLANT,wx.BOLD)
          self.panel.RatingMovieOn.SetForegroundColour(wx.WHITE)
          self.panel.RatingMovieOn.SetFont(font)
          self.panel.RatingMovieOn.SetBackgroundColour("#413f3f")
          self.panel.RatingMovie.SetBackgroundColour("#413f3f")
          #------------End of Rating--------------
               
          #------------Votes--------------
          #str = "Nothing"
          self.panel.VotesMovie = wx.StaticText(self, -1, '', pos = (795,245))
          font = wx.Font(12,wx.FONTFAMILY_ROMAN,wx.SLANT,wx.NORMAL)
          self.panel.VotesMovie.SetFont(font)
          self.panel.VotesMovie.SetForegroundColour(wx.WHITE)
          self.panel.VotesMovie.SetBackgroundColour("#413f3f")
          #------------End of Votes--------------
          
          #------------Description--------------
          #str = "Nothing"
          self.panel.DescriptionMovie = wx.StaticText(self, -1, '', pos = (550,455), size = (465,70), style = wx.TE_MULTILINE|wx.TE_WORDWRAP)
          font = wx.Font(12,wx.FONTFAMILY_ROMAN,wx.ITALIC,wx.NORMAL)
          self.panel.DescriptionMovie.SetFont(font)
          self.panel.DescriptionMovie.SetForegroundColour(wx.WHITE)
          self.panel.DescriptionMovie.SetBackgroundColour("#413f3f")
          self.panel.DescriptionMovie.Hide()
          #------------End of Description--------------
          
          #------------Reason for Reject--------------
          #str = "Nothing"
          self.panel.ReasonMovie = wx.StaticText(self, -1, '', pos = (550,525), size = (465,55), style = wx.TE_MULTILINE|wx.TE_WORDWRAP)
          font = wx.Font(12,wx.FONTFAMILY_ROMAN,wx.ITALIC,wx.NORMAL)
          self.panel.ReasonMovie.SetFont(font)
          self.panel.ReasonMovie.SetForegroundColour(wx.WHITE)
          self.panel.ReasonMovie.SetBackgroundColour("#413f3f")
          self.panel.ReasonMovie.Hide()
          #------------End of Reason for Reject--------------
          
          #------------Director and actors--------------
          #str = "Nothing"
          self.panel.DirectorsLabelMovie = wx.StaticText(self, -1, '', pos = (730,280))
          font = wx.Font(11,wx.FONTFAMILY_ROMAN,wx.SLANT,wx.BOLD)
          self.panel.DirectorsLabelMovie.SetForegroundColour(wx.WHITE)
          self.panel.DirectorsLabelMovie.SetBackgroundColour("#413f3f")
          self.panel.DirectorsLabelMovie.SetFont(font)
          
          self.panel.DirectorsMovie = wx.StaticText(self, -1, '', pos = (800,282))
          font = wx.Font(10,wx.FONTFAMILY_ROMAN,wx.SLANT,wx.NORMAL)
          self.panel.DirectorsMovie.SetFont(font)
          self.panel.DirectorsMovie.SetForegroundColour(wx.WHITE)
          self.panel.DirectorsMovie.SetBackgroundColour("#413f3f")
          
          self.panel.ActorsLabelMovie = wx.StaticText(self, -1, '', pos = (730,340))
          font = wx.Font(11,wx.FONTFAMILY_ROMAN,wx.SLANT,wx.BOLD)
          self.panel.ActorsLabelMovie.SetForegroundColour(wx.WHITE)
          self.panel.ActorsLabelMovie.SetBackgroundColour("#413f3f")
          self.panel.ActorsLabelMovie.SetFont(font)
          
          self.panel.ActorsMovie = wx.StaticText(self, -1, '', pos = (800,342), style = wx.TE_MULTILINE)
          font = wx.Font(10,wx.FONTFAMILY_ROMAN,wx.SLANT,wx.NORMAL)
          self.panel.ActorsMovie.SetForegroundColour(wx.WHITE)
          self.panel.ActorsMovie.SetBackgroundColour("#413f3f")
          self.panel.ActorsMovie.SetFont(font)
          #------------End of Directors and actors--------------
          
          #------------Status Download Image--------------
          # pick a .jpg file you have in the working folder
          
          self.imageFileDownload = './images/StatusDownload.gif'
          self.gif1 = wx.Image(self.imageFileDownload, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
          # bitmap upper left corner is in the position tuple (x, y) = (5, 5)
          self.panel.btnstatus = wx.StaticBitmap(self, -1, self.gif1, (610, 140), (50, 51))
          self.panel.btnstatus.Hide()
          #self.btnstatus.Bind(wx.EVT_BUTTON, self.OnDownload)
          
          #------Creation of Download Button + Event associated with it------          
          self.ImgStatus = "./images/download.png"
          ImgStatusimgImdb = wx.Bitmap(self.ImgStatus, wx.BITMAP_TYPE_PNG)
          self.panel.FileDownload = wx.Button(self.panel, 199, label='', pos=(590, 400), size=(70,60),style=wx.BORDER_NONE)
          self.panel.FileDownload.Bind(wx.EVT_BUTTON, self.OnDownload, id=-1)
          self.panel.FileDownload.SetBitmapLabel(ImgStatusimgImdb)
          self.panel.FileDownload.SetToolTip(wx.ToolTip("Download the movie"))
          #self.Bind(wx.EVT_BUTTON, self.OnDownload)
          self.panel.FileDownload.Hide()
          #------End of Creation of Download Button + Event associated with it------

          #------Creation of Trailer Button + Event associated with it------          
          self.ImgStatus = "./images/BtnTrailer.png"
          ImgStatusimgImdb = wx.Bitmap(self.ImgStatus, wx.BITMAP_TYPE_PNG)
          self.panel.FileTrailer = wx.Button(self.panel, -1, label='', pos=(790, 140), size=(50,51),style=wx.BORDER_NONE)
          self.panel.FileTrailer.Bind(wx.EVT_BUTTON, self.OnMovieTrailer, id=-1)
          self.Bind(wx.EVT_BUTTON, self.OnMovieTrailer)
          self.panel.FileTrailer.SetBitmapLabel(ImgStatusimgImdb)
          self.panel.FileTrailer.Hide()
          self.panel.FileTrailer.SetToolTip(wx.ToolTip("Watch the Trailer"))
          #------End of Creation of Trailer Button + Event associated with it------
          
          #------Creation of IMDB Button + Event associated with it------
          self.ImgStatus = "./images/BtnImdb.png"
          ImgStatusimgImdb = wx.Bitmap(self.ImgStatus, wx.BITMAP_TYPE_PNG)
          self.panel.ImdbBtn = wx.Button(self.panel, id=-1,size=(50,51),pos=(730, 140),style=wx.BORDER_NONE)
          self.panel.ImdbBtn.Bind(wx.EVT_BUTTON, self.ImdbBtnClick)
          self.panel.ImdbBtn.SetBitmapLabel(ImgStatusimgImdb)
          self.panel.ImdbBtn.Hide()
          self.panel.ImdbBtn.SetToolTip(wx.ToolTip("Open the movie in Imdb"))
          #------End of Creation of IMDB Button + Event associated with it------
          
          # pick a .jpg file you have in the working folder
          self.ImgStatus = "./images/BtnMatrix.png"
          self.ImgStatusimgIndexer = wx.Image(self.ImgStatus, wx.BITMAP_TYPE_PNG).ConvertToBitmap()
          # bitmap upper left corner is in the position tuple (x, y) = (5, 5)
          self.panel.ImgIndexer = wx.StaticBitmap(self, -1, self.ImgStatusimgIndexer, (670,140), (50, 51))
          self.panel.ImgIndexer.Hide()
          
          # pick a .jpg file you have in the working folder
          self.ImgStatus = "./images/BtnCouch.png"
          self.ImgStatusimgCouch = wx.Image(self.ImgStatus, wx.BITMAP_TYPE_PNG).ConvertToBitmap()
          # bitmap upper left corner is in the position tuple (x, y) = (5, 5)
          self.panel.ImgCouch = wx.StaticBitmap(self, -1, self.ImgStatusimgCouch, (910,140), (30, 30))
          self.panel.ImgCouch.Hide()

          # pick a .jpg file you have in the working folder
          self.ImgStatus = "./images/BtnCouch.png"
          self.ImgStatusimgCouchSnatched = wx.Image(self.ImgStatus, wx.BITMAP_TYPE_PNG).ConvertToBitmap()
          # bitmap upper left corner is in the position tuple (x, y) = (5, 5)
          self.panel.ImgCouchSnatched = wx.StaticBitmap(self, -1, self.ImgStatusimgCouchSnatched, (910,140), (50, 51))
          self.panel.ImgCouchSnatched.Hide()
          
          # pick a .jpg file you have in the working folder
          self.ImgStatus = "./images/BtnXbmc.png"
          self.ImgStatusimgXbmc = wx.Image(self.ImgStatus, wx.BITMAP_TYPE_PNG).ConvertToBitmap()
          # bitmap upper left corner is in the position tuple (x, y) = (5, 5)
          self.panel.ImgXbmc = wx.StaticBitmap(self, -1, self.ImgStatusimgXbmc, (850,140), (50, 51))
          self.panel.ImgXbmc.Hide()
          
          #------------End of Status Download Image--------------
          
          #------------Status Connection Image--------------
          self.imageInternetConnectionnzbsu = './images/icon03.jpg'
          self.gif2 = wx.Image(self.imageInternetConnectionnzbsu, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
          self.panel.InternetConnectionnzbsu = wx.StaticBitmap(self, -1, self.gif2, (805 + self.gif2.GetWidth(), 610), (self.gif2.GetWidth(), self.gif2.GetHeight()))
          
          # bitmap upper left corner is in the position tuple (x, y) = (5, 5)
          self.panel.InternetConnectionTextnzbsu = wx.StaticText(self, -1, 'Nzbsu Connection', pos = (845,610))
          font = wx.Font(9,wx.FONTFAMILY_ROMAN,wx.SLANT,wx.BOLD)
          self.panel.InternetConnectionTextnzbsu.SetForegroundColour(wx.WHITE)
          self.panel.InternetConnectionTextnzbsu.SetBackgroundColour("#575050")
          self.panel.InternetConnectionTextnzbsu.SetFont(font)
          
          # pick a .jpg file you have in the working folder
          
          self.imageInternetConnection = './images/icon03.jpg'
          self.gif2 = wx.Image(self.imageInternetConnection, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
          self.panel.InternetConnection = wx.StaticBitmap(self, -1, self.gif2, (805 + self.gif2.GetWidth(), 670), (self.gif2.GetWidth(), self.gif2.GetHeight()))
          
          # bitmap upper left corner is in the position tuple (x, y) = (5, 5)
          self.panel.InternetConnectionText = wx.StaticText(self, -1, 'Internet Connection', pos = (845,670))
          font = wx.Font(9,wx.FONTFAMILY_ROMAN,wx.SLANT,wx.BOLD)
          self.panel.InternetConnectionText.SetForegroundColour(wx.WHITE)
          self.panel.InternetConnectionText.SetBackgroundColour("#575050")
          self.panel.InternetConnectionText.SetFont(font)
          
          self.imageInternetConnectionnzbmatrix = './images/icon03.jpg'
          self.gif2 = wx.Image(self.imageInternetConnectionnzbmatrix, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
          self.panel.InternetConnectionnzbmatrix = wx.StaticBitmap(self, -1, self.gif2, (805 + self.gif2.GetWidth(), 650), (self.gif2.GetWidth(), self.gif2.GetHeight()))
          
          # bitmap upper left corner is in the position tuple (x, y) = (5, 5)
          self.panel.InternetConnectionTextnzbmatrix = wx.StaticText(self, -1, 'Nzbmatrix Connection', pos = (845,650))
          font = wx.Font(9,wx.FONTFAMILY_ROMAN,wx.SLANT,wx.BOLD)
          self.panel.InternetConnectionTextnzbmatrix.SetForegroundColour(wx.WHITE)
          self.panel.InternetConnectionTextnzbmatrix.SetBackgroundColour("#575050")
          self.panel.InternetConnectionTextnzbmatrix.SetFont(font)
          
          self.imageInternetConnectionimdb = './images/icon03.jpg'
          self.gif2 = wx.Image(self.imageInternetConnectionimdb, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
          self.panel.InternetConnectionimdb = wx.StaticBitmap(self, -1, self.gif2, (805 + self.gif2.GetWidth(), 630), (self.gif2.GetWidth(), self.gif2.GetHeight()))
          
          # bitmap upper left corner is in the position tuple (x, y) = (5, 5)
          self.panel.InternetConnectionTextimdb = wx.StaticText(self, -1, 'IMDB Connection', pos = (845,630))
          font = wx.Font(9,wx.FONTFAMILY_ROMAN,wx.SLANT,wx.BOLD)
          self.panel.InternetConnectionTextimdb.SetForegroundColour(wx.WHITE)
          self.panel.InternetConnectionTextimdb.SetBackgroundColour("#575050")
          self.panel.InternetConnectionTextimdb.SetFont(font)
     
          
          if config['couchpotato_connection'] == "no":
               self.imageConnectioncouchpotato = './images/Icon01.png'
          else:
               if self.isOpen(config['couchpotato_server'],config['couchpotato_port']):
                    self.imageConnectioncouchpotato = './images/Icon02.png'
               else:
                    self.imageConnectioncouchpotato = './images/Icon01.png'
               
          self.gif2 = wx.Image(self.imageConnectioncouchpotato, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
          self.panel.Connectioncouchpotato = wx.StaticBitmap(self, -1, self.gif2, (635 + self.gif2.GetWidth(), 670), (self.gif2.GetWidth(), self.gif2.GetHeight()))
          
          # bitmap upper left corner is in the position tuple (x, y) = (5, 5)
          self.panel.ConnectionTextcouchpotato = wx.StaticText(self, -1, 'CouchPotato Connection', pos = (675,670))
          font = wx.Font(9,wx.FONTFAMILY_ROMAN,wx.SLANT,wx.BOLD)
          self.panel.ConnectionTextcouchpotato.SetForegroundColour(wx.WHITE)
          self.panel.ConnectionTextcouchpotato.SetBackgroundColour("#575050")
          self.panel.ConnectionTextcouchpotato.SetFont(font)
          
          if config['xbmc_connection'] == "no":
               self.imageConnectionxbmc = './images/Icon01.png'
          else:
               if self.isOpen(config['xbmc_server'],config['xbmc_port']):               
                    self.imageConnectionxbmc = './images/Icon02.png'
               else:
                    self.imageConnectionxbmc = './images/Icon01.png'
          self.gif2 = wx.Image(self.imageConnectionxbmc, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
          self.panel.Connectionxbmc = wx.StaticBitmap(self, -1, self.gif2, (635 + self.gif2.GetWidth(), 650), (self.gif2.GetWidth(), self.gif2.GetHeight()))
          
          # bitmap upper left corner is in the position tuple (x, y) = (5, 5)
          self.panel.ConnectionTextxbmc = wx.StaticText(self, -1, 'XBMC Connection', pos = (675,650))
          font = wx.Font(9,wx.FONTFAMILY_ROMAN,wx.SLANT,wx.BOLD)
          self.panel.ConnectionTextxbmc.SetForegroundColour(wx.WHITE)
          self.panel.ConnectionTextxbmc.SetBackgroundColour("#575050")
          self.panel.ConnectionTextxbmc.SetFont(font)
          
          self.imageInternetConnectionnzbs = './images/icon03.jpg'
          self.gif2 = wx.Image(self.imageInternetConnectionnzbs, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
          self.panel.InternetConnectionNzbs = wx.StaticBitmap(self, -1, self.gif2, (635 + self.gif2.GetWidth(), 630), (self.gif2.GetWidth(), self.gif2.GetHeight()))
          
          # bitmap upper left corner is in the position tuple (x, y) = (5, 5)
          self.panel.InternetConnectionTextnzbs = wx.StaticText(self, -1, 'Nzbs Connection', pos = (675,630))
          font = wx.Font(9,wx.FONTFAMILY_ROMAN,wx.SLANT,wx.BOLD)
          self.panel.InternetConnectionTextnzbs.SetForegroundColour(wx.WHITE)
          self.panel.InternetConnectionTextnzbs.SetBackgroundColour("#575050")
          self.panel.InternetConnectionTextnzbs.SetFont(font)
          
          #------------End of Status Connection Image--------------
          
          #------------Legend Image--------------
          
          ag_fname2 = "./images/legend.jpg"
          self.jpg1 = wx.Image(ag_fname2, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
          # bitmap upper left corner is in the position tuple (x, y) = (5, 5)
          self.panel.Arrow = wx.StaticBitmap(self, -1, self.jpg1, pos=(5, 600), size=(self.jpg1.GetWidth(), self.jpg1.GetHeight()))
          
          #------------End of Legend Image--------------
          
          #------------AutoCheck Movie Checkbox--------------
          self.panel.AutoCheck = wx.CheckBox( self.panel, -1, 'Automatically check for new movies',pos=(13, 101) )
          self.panel.AutoCheck.Bind(wx.EVT_CHECKBOX,self.ChangeAutoTimer)
          #------------End of AutoCheck Movie Checkbox--------------
          
          
          #|*******************************************************************************************|
          #|End of Panel Movie Info creation                                                           |
          #|*******************************************************************************************|
        
          #------Creation of the Thread------
          self.r = RepeatTimer(int(config['IntervalCheck']),self.CheckMovieTimer)
          #------End of Creation of the Thread------
          
          #------Creation of the Thread------
          self.rint = RepeatTimer(20,self.CheckConnection)
          self.rint.start()
          #------End of Creation of the Thread------
          
          #------Creation of the Thread------
          self.rintonce = RepeatTimer(1,self.CheckConnection,1)
          self.rintonce.start()
          #------End of Creation of the Thread------
          
          #------Global Variable------
          self.Server = ""
          self.ImdbLinkbtn=""
          self.wait = 0
          #------End of Global Variable------
          
          
     def OnClearConsoleLog(self,event):
          fileIN = open("./crazybeaver_console.log", "w")
          fileIN.close()
          self.bar.SetStatusText("Console Log Cleared",1)
          self.info.ShowMessage("Console Log Cleared", wx.ICON_INFORMATION)
          #------Creation of the Thread to dimiss the InfoBar after 20 secs------
          self.rInfo = RepeatTimer(20,self.StopInfoBar,1)
          self.rInfo.start()
          #------End of Creation of the Thread------

     def OnClearWarningLog(self,event):
          fileIN = open("./crazybeaver_warning.log", "w")
          fileIN.close()
          self.bar.SetStatusText("Warning Log Cleared",1)
          self.info.ShowMessage("Warning Log Cleared", wx.ICON_INFORMATION)
          #------Creation of the Thread to dimiss the InfoBar after 20 secs------
          self.rInfo = RepeatTimer(20,self.StopInfoBar,1)
          self.rInfo.start()
          #------End of Creation of the Thread------
          
     def OnClearErrorLog(self,event):
          fileIN = open("./crazybeaver_error.log", "w")
          fileIN.close()
          self.bar.SetStatusText("Error Log Cleared",1)
          self.info.ShowMessage("Error Log Cleared", wx.ICON_INFORMATION)
          #------Creation of the Thread to dimiss the InfoBar after 20 secs------
          self.rInfo = RepeatTimer(20,self.StopInfoBar,1)
          self.rInfo.start()
          #------End of Creation of the Thread------

     def OnConsoleLog(self,event):
          self.frame = wx.Frame(None, -1, '')
          self.frame.SetToolTip(wx.ToolTip('This is the Console Log'))
          self.frame.SetPosition(wx.Point(20,20))
          self.frame.SetSize(wx.Size(600,600))
          self.frame.SetTitle('Console Log')
          #------------Console Log Text--------------
          self.ConsoleLogText = wx.TextCtrl(self.frame, -1, '', pos = (0,0), size = (600,600), style = wx.TE_MULTILINE)
          font = wx.Font(8,wx.FONTFAMILY_MODERN,wx.SLANT,wx.NORMAL)
          self.ConsoleLogText.SetFont(font)
          self.ConsoleLogText.Show()
          #------------End of Console Log Text--------------
          try:
               fileIN = open("./crazybeaver_console.log", "r")
               line = fileIN.readline()
 
               while line:
                    self.ConsoleLogText.AppendText(line)
                    line = fileIN.readline()
          except:
               self.ConsoleLogText.AppendText("")
          
          self.frame.Show()

     def OnMovieTrailer(self,event):
          
          p=subprocess.Popen('"' + config['vlc_path'] + 'vlc.exe"' + imdb_movie_trailer, shell=False,stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)          
          

     def OnCouchCheck(self,event):
          Temp = self.panel.MovieCouchBtn.GetLabel()
          self.panel.MovieCouchBtn.SetLabel("Please Wait...")
          frameCouch = wx.Frame(None, -1, '')
          frameCouch .SetToolTip(wx.ToolTip('This is the CouchPotato Watch List'))
          frameCouch .SetPosition(wx.Point(20,20))
          frameCouch .SetSize(wx.Size(650,600))
          frameCouch.SetBackgroundColour("white")
          frameCouch .SetTitle('CouchPotato Watch List')
          scroll = wx.ScrolledWindow(frameCouch,-1,size=(650,585)) # our scroll area where we'll put everything
          
          ag_fname2 = "./images/topcouch.jpg"
          self.jpg1 = wx.Image(ag_fname2, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
          # bitmap upper left corner is in the position tuple (x, y) = (5, 5)
          self.panel.Arrow = wx.StaticBitmap(frameCouch, -1, self.jpg1, pos=(1, 1), size=(self.jpg1.GetWidth(), self.jpg1.GetHeight()))

          #------Opening connection to CouchPotato DB------          
          connCouch = sqlite.connect(config['couchpotato_path'] + 'data.db')
          connCouch.row_factory = sqlite.Row
          cCouch = connCouch.cursor()   
          cCouch.execute("select name,imdb from Movie where status='want'")
          
          #------Opening connection to Histo DB------          
          connHisto = sqlite.connect('./History.db')
          connHisto.row_factory = sqlite.Row
          cHisto = connHisto.cursor()

          VarHeight = 1
          i=100
          for rowCouch in cCouch:
               found = 0
               cHisto.execute('select Title  from Movie where ImdbId = "' + rowCouch["imdb"] +'"')
               for rowHisto in cHisto:
                    if found == 0:
                         VarheightBtn = VarHeight+10
                         IMDBVarModPoster(rowCouch["imdb"])
                         found = 1
                         try:
                              fp = urllib.urlopen(imdb_movie_imagePoster)
                              data = fp.read()
                              fp.close()
                              ImgPoster = wx.ImageFromStream(StringIO(data))
                              ImgPoster = ImgPoster.Scale(134, 200, wx.IMAGE_QUALITY_HIGH)
                              imagetemp = wx.StaticBitmap(scroll, -1, wx.BitmapFromImage(ImgPoster), size=(134, 200),pos=(1, VarHeight))
                         except:
                              ImgPoster = wx.Image(self.imageFile, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
                              imagetemp = wx.StaticBitmap(scroll, -1, ImgPoster, size=(134, 200),pos=(1, VarHeight))
                         VarHeight = VarHeight + 215
                         MovieBtn = wx.Button(scroll, id=i, label=rowHisto["Title"],pos=(150, VarheightBtn+5), size=(450,20))
                         MovieBtn.Bind(wx.EVT_BUTTON, self.OnDownload)
                         
                    else:
                         VarheightBtn = VarheightBtn + 25
                         MovieBtn = wx.Button(scroll, id=i, label=rowHisto["Title"],pos=(150, VarheightBtn+5), size=(450,20))
                         MovieBtn.Bind(wx.EVT_BUTTON, self.OnDownload)
                    i = i + 1
               
          #------End of Opening connection to CouchPotato DB------
                    
          cCouch.close()
          cHisto.close()

          width, height = scroll.GetBestSize()
          scroll.SetScrollbars(1, 1, 580, height) # throwing up some scrollbars
          frameCouch.Show()
          self.panel.MovieCouchBtn.SetLabel(Temp)
     
     def OnWarningLog(self,event):
          self.frame = wx.Frame(None, -1, '')
          self.frame.SetToolTip(wx.ToolTip('This is the Warning Log'))
          self.frame.SetPosition(wx.Point(20,20))
          self.frame.SetSize(wx.Size(600,600))
          self.frame.SetTitle('Warning Log')
          #------------Warning Log Text--------------
          self.WarningLogText = wx.TextCtrl(self.frame, -1, '', pos = (0,0), size = (600,600), style = wx.TE_MULTILINE)
          font = wx.Font(8,wx.FONTFAMILY_MODERN,wx.SLANT,wx.NORMAL)
          self.WarningLogText.SetFont(font)
          self.WarningLogText.Show()
          #------------End of Warning Log Text--------------
          try:
               fileIN = open("./crazybeaver_warning.log", "r")
               line = fileIN.readline()
 
               while line:
                    self.WarningLogText.AppendText(line)
                    line = fileIN.readline()
          except:
               self.WarningLogText.AppendText("")
          
          self.info.Dismiss()
          self.frame.Show()

     def OnErrorLog(self,event):
          self.frameError = wx.Frame(None, -1, '')
          self.frameError.SetToolTip(wx.ToolTip('This is the Warning Log'))
          self.frameError.SetPosition(wx.Point(20,20))
          self.frameError.SetSize(wx.Size(600,600))
          self.frameError.SetTitle('Error Log')
          #------------Error Log Text--------------
          self.ErrorLogText = wx.TextCtrl(self.frameError, -1, '', pos = (0,0), size = (600,600), style = wx.TE_MULTILINE)
          font = wx.Font(8,wx.FONTFAMILY_MODERN,wx.SLANT,wx.NORMAL)
          self.ErrorLogText.SetFont(font)
          self.ErrorLogText.Show()
          #------------End of Error Log Text--------------        
          try:
               fileIN = open("./crazybeaver_error.log", "r")
               line = fileIN.readline()
 
               while line:
                    self.ErrorLogText.AppendText(line)
                    line = fileIN.readline()
          except:
               self.ErrorLogText.AppendText("")
          
          self.info.Dismiss()
          self.frameError.Show()

     def ImdbBtnClick(self,event):
          webbrowser.open(self.panel.ImdbLinkbtn)
          
     def DonateBtnClick(self,event):
          webbrowser.open("https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=lclement%40gmail%2ecom&lc=BE&item_name=Crazy%20Beaver&no_note=0&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donate_SM%2egif%3aNonHostedGuest")
          
     def isOpen(self,ip,port):
          s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
          try:
               s.connect((ip, int(port)))
               s.shutdown(2)
               return True
          except:
               return False
     
     def CheckConnection(self):
          #execute the code and pipe the result to a string
          pingtest = "ping google.com"
          process = subprocess.Popen(pingtest, shell=True, stdout=subprocess.PIPE)
          #wait for ping process to complete
          process.wait()

          #check return code
          if process.returncode == 0:
              
               ImgStatusInternet = "./images/Icon02.png"
   
          else:
               ImgStatusInternet = "./images/Icon01.png"
          
          ImgStatusimgInternet = wx.Image(ImgStatusInternet, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
          self.panel.InternetConnection.SetBitmap(ImgStatusimgInternet)
          self.panel.InternetConnection.Show()
          
          #execute the code and pipe the result to a string
          pingtest = "ping nzbmatrix.com"
          process = subprocess.Popen(pingtest, shell=True, stdout=subprocess.PIPE)
          #wait for ping process to complete
          process.wait()

          #check return code
          if process.returncode == 0:
              
               ImgStatusInternet = "./images/Icon02.png"
   
          else:
               ImgStatusInternet = "./images/Icon01.png"
          
          ImgStatusimgInternet = wx.Image(ImgStatusInternet, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
          self.panel.InternetConnectionnzbmatrix.SetBitmap(ImgStatusimgInternet)
          
          #execute the code and pipe the result to a string
          try:
               data = urllib.urlopen("http://labs.imdb.com").read()          
          except Exception:
               ImgStatusInternet = "./images/Icon01.png"
          else:
               ImgStatusInternet = "./images/Icon02.png"
          
          ImgStatusimgInternet = wx.Image(ImgStatusInternet, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
          self.panel.InternetConnectionimdb.SetBitmap(ImgStatusimgInternet)
          
          if config['couchpotato_connection'] == "no":
               imageConnectioncouchpotato = './images/icon01.jpg'
          else:
               if self.isOpen(config['couchpotato_server'],config['couchpotato_port']):
                    imageConnectioncouchpotato = './images/Icon02.png'
               else:
                    imageConnectioncouchpotato = './images/Icon01.png'
          gif2 = wx.Image(imageConnectioncouchpotato, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
          self.panel.Connectioncouchpotato.SetBitmap(gif2)
          
          
          if config['xbmc_connection'] == "no":
               imageConnectionxbmc = './images/icon01.jpg'
          else:
               if self.isOpen(config['xbmc_server'],config['xbmc_port']):               
                    imageConnectionxbmc = './images/Icon02.png'
               else:
                    imageConnectionxbmc = './images/Icon01.png'               
               
          gif2 = wx.Image(imageConnectionxbmc, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
          self.panel.Connectionxbmc.SetBitmap(gif2)
          
          #execute the code and pipe the result to a string
          try:
               data = urllib.urlopen("http://nzbs.org").read()          
          except Exception:
               ImgStatusNzbs = "./images/Icon01.png"
          else:
               ImgStatusNzbs = "./images/Icon02.png"
          
          ImgStatusimgNzbs = wx.Image(ImgStatusNzbs, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
          self.panel.InternetConnectionNzbs.SetBitmap(ImgStatusimgNzbs)
          
          #execute the code and pipe the result to a string
          try:
               data = urllib.urlopen("http://nzb.su").read()          
          except Exception:
               ImgStatusNzbsu = "./images/Icon01.png"
          else:
               ImgStatusNzbsu = "./images/Icon02.png"
          
          ImgStatusimgNzbsu = wx.Image(ImgStatusNzbsu, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
          self.panel.InternetConnectionnzbsu.SetBitmap(ImgStatusimgNzbsu)
          
     def ChangeAutoTimer(self, event):
          if self.panel.AutoCheck.GetValue():
               self.r.start()
               
          else:
               self.r.cancel()
               self.r = RepeatTimer(60.0,self.CheckMovieTimer)
               
     def OnDownload(self, event):
          
          try:          
               self.panel.FileDownload.Disable()
               #save nzb file in watched folder
               #login to nzbmatrix using mechanize
               browser2 = mechanize.Browser()
               browser2.addheaders = [('User-agent', "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)")]
     
               #------Opening connection to Histo DB------          
               connHisto = sqlite.connect('./History.db')
               connHisto.row_factory = sqlite.Row
               cHisto = connHisto.cursor()

               btn = event.GetEventObject()
               Result = btn.GetLabel()
               IdBtn = btn.GetId()

               if IdBtn == 199:
                    ToSearch = str(self.Select)
               else:
                    ToSearch = Result
               sql = "select Id,ImdbTitle,ImdbId,Indexer from Movie where Title='" + ToSearch + "'"
               cHisto.execute(sql)
               #------End of Opening connection to Histo DB------
               for row in cHisto:
                    if row["Indexer"] == "nzbmatrix":                         
                         #sleep and retry to read the login page for nzbmatrix 5 times with 30 sec gap
                         try:
                              #nzbmatrix login url                              
                              nzbmatrix_login_url = "https://nzbmatrix.com/index.php"
                              self.bar.SetStatusText("Login to nzbmatrix...",1)
                              #nzbmatrix search url
                              #nzbmatrix_search_url = "https://nzbmatrix.com/nzb-search.php?search=" + nzbmatrix_search + "&cat=" + nzbmatrix_cat + "&searchin=name&maxage=0&grp=&larger=" + nzbmatrix_minsize + "&smaller=" + nzbmatrix_maxsize + "&minhits=0&maxhits=0&sort=0&type=asc&weblinkonly=1&englishonly=" + nzbmatrix_lang
                              browser2.open(nzbmatrix_login_url)
                              browser2.select_form(nr=0)
                              browser2['username'] = config['nzbmatrix_username']
                              browser2['password'] = config['nzbmatrix_password']
                              browser2.submit()
                              break
               
                         except:
                              OpenLoginRetryCount += 1
                              time.sleep(10)
     
                         else:
                              self.bar.SetStatusText("Nzbmatrix Login Down",1)
                              return
                    else:
                         break
               #------Opening connection to Histo DB------          
               
               sql = "select Id,ImdbTitle,ImdbId,Indexer from Movie where Title='" + ToSearch + "'"
               cHisto.execute(sql)
               #------End of Opening connection to Histo DB------
     
               for row in cHisto:
                    self.bar.SetStatusText("Downloading Movie " + row["ImdbTitle"],1)
                    if row["Indexer"] == "nzbmatrix":
                         essai = browser2.retrieve("http://nzbmatrix.com/nzb-download.php?id=" + row["Id"] + "&nozip=1", config['watch_dir'] + row["ImdbTitle"] + ".nzb")
                    else:
                         if row["Indexer"] == "nzbs":
                              #change useragent to look like windows 7 running ie8 (used for freecovers)
                              class AppURLopener(urllib.FancyURLopener):
                                   version = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)"
                              urllib._urlopener = AppURLopener()                              
                              #save nzb file in watched folder
                              urllib.urlretrieve("http://nzbs.org/index.php?action=getnzb&nzbid=" + row["Id"] + config['nzbs_rss_directdl'], config['watch_dir'] + imdb_movie_title + ".nzb")
                         else:                                                                      
                              nzbsu_download_link = "http://www.nzb.su/api?t=get&id=" +  row["Id"] + "&apikey=" + config['nzbsu_key']
                              browser2.retrieve("http://www.nzb.su/api?t=get&id=" +  row["Id"] + "&apikey=" + config['nzbsu_key'], config['watch_dir'] + imdb_movie_title + ".nzb")
                              
                    #------Opening connection to CouchPotato DB------          
                    connCouch = sqlite.connect(config['couchpotato_path'] + 'data.db')
                    connCouch.row_factory = sqlite.Row
                    cCouch = connCouch.cursor()   
                    essai = "update Movie set status='deleted' where imdb='" + row["ImdbId"] + "'"
                    cCouch.execute("select Id from Movie where imdb='" + row["ImdbId"] + "' and status='want'")
                    for rowCouch in cCouch:  
                         if config['couchpotato_connection'] == "yes" and rowCouch["Id"]:
                              answer = wx.MessageBox("Don't you want to remove that movie from CouchPotato?",style = wx.YES_NO | wx.CENTRE)
                              if (answer == wx.YES):
                                   urllib.urlopen("http://localhost:5000/movie/delete/?id=" + str(rowCouch["Id"]))
                    #------End of Opening connection to CouchPotato DB------
                              
                    cCouch.close()
                    ImgStatus = "./images/BtnOk.png"
                    ImgStatusimg = wx.Image(ImgStatus, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
                    self.panel.btnstatus.SetBitmap(ImgStatusimg)
                    self.panel.ImgCouch.Hide()
                    self.bar.SetStatusText("Movie " + row["ImdbTitle"] + " downloaded with success",1)
                    cHisto.execute("update Movie set Downloaded='yes' where Title='" + ToSearch + "'")
                    connHisto.commit()
               cHisto.close()
               self.UpdateHisto(3)
               self.panel.FileDownload.Enable()
               self.info.ShowMessage("Movie Downloaded with Success !", wx.ICON_INFORMATION)
               #------Creation of the Thread to dimiss the InfoBar after 20 secs------
               self.rInfo = RepeatTimer(20,self.StopInfoBar,1)
               self.rInfo.start()
               #------End of Creation of the Thread------
          except:
               self.UpdateHisto(4)
               self.bar.SetStatusText("Movie Download Failed :" + row["ImdbTitle"],1)
               self.info.ShowMessage("Movie Download Failed :" + row["ImdbTitle"], wx.ICON_ERROR)
               #------Creation of the Thread to dimiss the InfoBar after 20 secs------
               self.rInfo = RepeatTimer(20,self.StopInfoBar,1)
               self.rInfo.start()
               #------End of Creation of the Thread------               
               self.panel.FileDownload.Enable()

     def ListEvtKeyDown(self, event):
          keycode = event.GetKeyCode() 
          #print "Event handler `ListEvtKeyDown' " + str(keycode) 
          if keycode == wx.WXK_DELETE: 
               self.list.DeleteItem(self.list.GetFocusedItem())
               
     def OnDelete(self, event):
          #self.list.DeleteItem(self.list.GetFocusedItem())
          self.t.start()

     def OnSelect(self, event):
          #self.panel.ag.Play()          
          index = event.GetSelection()
          time_zone = event.GetItem()
          self.Select = time_zone.GetText()
          IdList = self.panel.list.GetItem(event.GetIndex(),3)
          IdList = IdList.GetText()
          #|*******************************************************************************************|
          #|Panel Movie Info Fill in with the selected Movie                                           |
          #|*******************************************************************************************|
          #------Opening the connection the to Histo DB and Get the infos related to the selection------ 
          connHisto = sqlite.connect('./History.db')
          connHisto.row_factory = sqlite.Row
          cHisto = connHisto.cursor()
          cHisto.execute("select * from Movie where Title='" + time_zone.GetText() + "' and Id='" + IdList + "'")
          #------End of Opening the connection the to Histo DB and Get the infos related to the selection------
          
          for row in cHisto:
               returnimdb = IMDBVarMod(row["ImdbId"])
               reason = row["Reason"]
               downloaded = row["Downloaded"]
               self.panel.ImdbLinkbtn = row["Link"]
               break
               
          if returnimdb == "IMDB API ERROR":
               self.panel.TitleMovie.SetLabel("Unable to get informations from IMDB")
               font = wx.Font(14,wx.FONTFAMILY_ROMAN,wx.SLANT,wx.BOLD)
               self.panel.TitleMovie.SetForegroundColour(wx.RED)
               self.panel.TitleMovie.SetFont(font)
               self.panel.GenreMovie.SetLabel("")
               self.panel.RatingMovie.SetLabel("")
               self.panel.RatingMovieOn.SetLabel("")
               self.panel.VotesMovie.SetLabel("")
               self.panel.DescriptionMovie.SetLabel("")
               self.panel.ActorsMovie.SetLabel("")
               self.panel.DirectorsMovie.SetLabel("")
               self.panel.ActorsLabelMovie.SetLabel("")
               self.panel.DirectorsLabelMovie.SetLabel("")
               self.panel.DescriptionMovie.Hide()
               self.panel.ImgXbmc.Hide()
               self.panel.ImgCouch.Hide()
               self.panel.ReasonMovie.Hide()
               self.panel.FileDownload.Show()
               self.panel.ImgIndexer.Hide()
               self.panel.FileTrailer.Hide()
               self.panel.ImgCouchSnatched.Hide()
               #------Status Download Image
               if  row["Downloaded"] == "yes":
                    ImgStatus = "./images/BtnOk.png"
               else:
                    ImgStatus = "./images/BtnNotOk.png"
               ImgStatusimg = wx.Image(ImgStatus, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
               self.panel.btnstatus.SetBitmap(ImgStatusimg)
               self.panel.btnstatus.Show()
               self.panel.Poster.Show()
               #------End of Status Download Image
               
               noinfojpg = wx.Image(self.imageFile, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
               self.panel.Poster.SetBitmap(noinfojpg)
               noinfojpg = wx.Image(self.imageFileDownload, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
          else:
               #------Writing the name of the Movie     
               #self.panel.TitleMovie.SetForegroundColour(wx.WHITE) 
               #self.panel.TitleMovie.Destroy()
               #self.panel.TitleMovie = wx.StaticText(self, -1, imdb_movie_title + "  (" + str(imdb_movie_year) + ")", pos = (730,145))
               #font = wx.Font(12,wx.FONTFAMILY_ROMAN,wx.SLANT,wx.BOLD)
               #self.panel.TitleMovie.SetFont(font)
               #self.panel.TitleMovie.SetBackgroundColour("#413f3f")
               #self.panel.TitleMovie.SetForegroundColour(wx.WHITE)
               self.panel.TitleMovie.SetLabel(imdb_movie_title + "  (" + str(imdb_movie_year) + ")")
               #font = wx.Font(14,wx.FONTFAMILY_ROMAN,wx.SLANT,wx.BOLD)
               #self.panel.TitleMovie.SetFont(font)
               #self.panel.TitleMovie.SetBackgroundColour("#413f3f")
               #------End of Writing the name of the Movie
               
               #------Try to take the Movie Poster from IMDB
               if config['EnablePoster'] == "yes":
                    try:
                         fp = urllib.urlopen(imdb_movie_image)
                         data = fp.read()
                         fp.close()
                         ImgPoster = wx.ImageFromStream(StringIO(data))
                         ImgPoster = ImgPoster.Scale(134, 200, wx.IMAGE_QUALITY_HIGH)
                         self.panel.Poster.SetBitmap(wx.BitmapFromImage(ImgPoster))
                    except:
                         # No Image found from IMDB
                         # or there could be a problem getting the data
                         # or the data might not be a valid jpeg, png...
                         # so loading the NOPOSTER.jpg
                         noinfojpg = wx.Image(self.imageFile, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
                         self.panel.Poster.SetBitmap(noinfojpg)
                         noinfojpg = wx.Image(self.imageFileDownload, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
               else:
                    noinfojpg = wx.Image(self.imageFile, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
                    self.panel.Poster.SetBitmap(noinfojpg)
               self.panel.Poster.Show()
               
               #------End of Try to take the Movie Poster from IMDB
               
               #------Writing Genres of the Movie 
               imdb_movie_genresTemp = ""
               for genretemp in imdb_movie_genres:
                    imdb_movie_genresTemp = imdb_movie_genresTemp + genretemp + ", "
               
               self.panel.GenreMovie.SetLabel(str(imdb_movie_genresTemp))
               self.panel.GenreMovie.SetBackgroundColour("#413f3f")
               #------End of Writing genres of the Movie
               
               #------Writing Rating of the Movie 
               self.panel.RatingMovie.SetLabel(str(imdb_movie_rating))
               self.panel.RatingMovieOn.SetBackgroundColour("#413f3f")
               self.panel.RatingMovie.SetBackgroundColour("#413f3f")
               font = wx.Font(15,wx.FONTFAMILY_ROMAN,wx.SLANT,wx.BOLD)
               self.panel.RatingMovie.SetForegroundColour("gold")
               self.panel.RatingMovie.SetFont(font)
               self.panel.RatingMovieOn.SetLabel(" / 10  ")
               
               #------End of Rating of the Movie
               
               #------Writing Votes of the Movie 
               self.panel.VotesMovie.SetLabel("--- " + str(imdb_movie_votes) + " votes")
               self.panel.VotesMovie.SetBackgroundColour("#413f3f")
               #------End of Votes of the Movie
               
               #------Writing Desciption of the Movie 
               self.panel.DescriptionMovie.SetLabel(str(imdb_movie_description))
               self.panel.DescriptionMovie.Show()
               self.panel.DescriptionMovie.SetBackgroundColour("#413f3f")
               #------End of Description of the Movie
               
               #------Writing Reasons of Reject 
               if row["Reason"] == "":
                    self.panel.ReasonMovie.Hide()
               else:
                    self.panel.ReasonMovie.SetLabel(row["Reason"])
                    self.panel.ReasonMovie.Show()
                    self.panel.ReasonMovie.SetBackgroundColour("#413f3f")
               #------End of Reasons of Reject
               
               #------Writing Directors and Actors of the Movie 
               self.panel.DirectorsLabelMovie.SetLabel("Directors")
               imdb_movie_directorsTemp = ""
               
               for imdb_movie_director in imdb_movie_directors:
                    if imdb_movie_director == 'U':
                         break
                    else:
                         imdb_movie_directorsTemp = imdb_movie_directorsTemp + imdb_movie_director["name"]["name"] + "\n"
               self.panel.DirectorsMovie.SetLabel(imdb_movie_directorsTemp)
               self.panel.DirectorsMovie.SetBackgroundColour("#413f3f")
               
               self.panel.ActorsLabelMovie.SetLabel("Actors")
               imdb_movie_actorsTemp = ""
               for imdb_movie_actor in imdb_movie_cast_members:
                    if imdb_movie_actor == 'U':
                         break
                    else:
                         imdb_movie_actorsTemp = imdb_movie_actorsTemp + imdb_movie_actor["name"]["name"] + "\n"
               self.panel.ActorsMovie.SetLabel(imdb_movie_actorsTemp)
               self.panel.ActorsMovie.SetBackgroundColour("#413f3f")
               #------End of Directors and Actors of the Movie
               
               #------IMDB Link Button
               #------End of IMDB Link Button
               
               #------Status Download Image
               if  row["Downloaded"] == "yes":
                    ImgStatus = "./images/BtnOk.png"
               else:
                    ImgStatus = "./images/BtnNotOk.png"
               ImgStatusimg = wx.Image(ImgStatus, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
               self.panel.btnstatus.SetBitmap(ImgStatusimg)
               self.panel.btnstatus.Show()
               
               if  row["Indexer"] == "nzbmatrix":
                    ImgStatus = "./images/BtnMatrix.png"
               else:
                    if row["Indexer"] == "nzbs":
                         ImgStatus = "./images/BtnNzbs.png"
                    else:
                         ImgStatus = "./images/BtnNzbsu.png"
               ImgStatusimg = wx.Image(ImgStatus, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
               self.panel.ImgIndexer.SetBitmap(ImgStatusimg)
               self.panel.ImgIndexer.Show()
               
               self.panel.ImgCouch.Hide()
               self.panel.ImgCouchSnatched.Hide()
               if config['couchpotato_connection'] == "yes":
                    #------Opening connection to CouchPotato DB------          
                    connCouch = sqlite.connect(config['couchpotato_path'] + 'data.db')
                    connCouch.row_factory = sqlite.Row
                    cCouch = connCouch.cursor()
                    cCouch.execute('select name, status from Movie where name="' + row["ImdbTitle"] + '" AND (status ="want" OR status="snatched")')
                    #------End of Opening connection to CouchPotato DB------
                    
                    for rowCouch in cCouch:
                         if row["ImdbTitle"] == rowCouch["name"]:
                              if rowCouch["status"] == "snatched":
                                   self.panel.ImgCouchSnatched.Show()
                              else:
                                   self.panel.ImgCouch.Show()
                         else:
                              self.panel.ImgCouch.Hide()
                         
                    cCouch.close()
                    
               self.panel.ImgXbmc.Hide()
               if config['xbmc_connection'] == "yes":
                    #------Opening connection to CouchPotato DB------          
                    connXbmc = sqlite.connect(config['xbmc_path'] + 'MyVideos34.db')
                    connXbmc.row_factory = sqlite.Row
                    cXbmc = connXbmc.cursor()
                    cXbmc.execute('select c00 from movie where c00="' + row["ImdbTitle"] + '"')
                    #------End of Opening connection to CouchPotato DB------
                    
                    for rowXbmc in cXbmc:
                         if row["ImdbTitle"] == rowXbmc["c00"]:
                              self.panel.ImgXbmc.Show()
                         else:
                              self.panel.ImgXbmc.Hide()
                         
                    cXbmc.close()
               self.panel.FileDownload.Show()
               self.panel.ImdbBtn.Show()
               #------End of Status Download Image
               if imdb_movie_trailer:
                    self.panel.FileTrailer.Show()
               else:
                    self.panel.FileTrailer.Hide()
          
               
          #|*******************************************************************************************|
          #|End of Panel Movie Info Fill in with the selected Movie                                    |
          #|*******************************************************************************************|
          #self.panel.ag.Stop()
     def OnExit(self, evt):
          self.r.cancel()
          self.rint.cancel()
          self.Destroy()

     #def OnConfig(self, evt):
          #self.panel.etiquette.SetLabel("no")

     def UpdateHisto(self,wait):
          
          #------Opening the connection to the Histo DB------          
          connHisto = sqlite.connect('./History.db')
          connHisto.row_factory = sqlite.Row
          cHisto = connHisto.cursor()

          d=datetime.datetime.now()-timedelta(days=int(config['history_display_days']))
          cHisto.execute('select * from Movie where date > "' + str(d) + '" ORDER BY date desc')
          #------End of Opening the connection to the Histo DB------
          
          #------Fill in the ListCtrl------
          self.panel.list.DeleteAllItems()
          i = 0
          for row in cHisto:
               img =  self.il_max
               temp = row["Title"]
               temp = temp.replace(",","")
               temp = temp.replace("'","")
               if row["New"] == "yes" :
                    if row["Downloaded"] == "yes" :
                         img =  self.il_maxNewOk
                    else:
                         img =  self.il_maxNewNOk
               else:
                    if row["Downloaded"] == "yes" :
                         img =  self.il_maxGood
                    else :
                         
                         if config['couchpotato_connection'] == "yes":
                              #------Opening connection to CouchPotato DB------          
                              connCouch = sqlite.connect(config['couchpotato_path'] + 'data.db')
                              connCouch.row_factory = sqlite.Row
                              cCouch = connCouch.cursor()
                              cCouch.execute('select name, status from Movie where name="' + row["ImdbTitle"] + '" AND (status="want" OR status="snatched")')
                              #------End of Opening connection to CouchPotato DB------
                              img =  self.il_max
                              for rowCouch in cCouch:
                                   if row["ImdbTitle"] == rowCouch["name"]:
                                        if rowCouch["status"] == "snatched":
                                             img =  self.il_maxCouchSnatched
                                        else:
                                             img =  self.il_maxCouch
                                   else:
                                        img =  self.il_max
                              cCouch.close()          
                         if config['xbmc_connection'] == "yes":
                              #------Opening connection to XBMC DB------ 
                              connXbmc = sqlite.connect(config['xbmc_path'] + 'MyVideos34.db')
                              connXbmc.row_factory = sqlite.Row
                              cXbmc = connXbmc.cursor()
                              cXbmc.execute('select c00 from movie where c00="' + row["ImdbTitle"] + '"')
                              #------End of Opening connection to XBMC DB------
                                        
                              for rowXbmc in cXbmc:
                                   if row["ImdbTitle"] == rowXbmc["c00"]:
                                        img =  self.il_maxXbmc
                                        
                              cXbmc.close()    
                         
               self.panel.list.InsertImageStringItem(i, temp, img)
               self.panel.list.SetStringItem(i,1,row["Indexer"])
               self.panel.list.SetStringItem(i,2,row["Date"])
               self.panel.list.SetStringItem(i,3,row["Id"])
               i = i + 1
          #------End of Fill in the ListCtrl------
          
          cHisto.close()
          
          #------Reactivation of the Check Movie Button + Stop the Animated Gif Loading------
          self.panel.CheckMovieBtn.Enable()
          Img = wx.Bitmap("./images/checkmovies.jpg", wx.BITMAP_TYPE_JPEG)
          self.panel.CheckMovieBtn.SetBitmapLabel(Img)
          #self.panel.CheckMovieBtn.SetLabel("Check for new movies")
          #self.panel.ag.Stop()
          #------End of eactivation of the Check Movie Button + Stop the Animated Gif Loading------
          
          now = datetime.datetime.now()
          self.bar.SetStatusText("Last Check : " + now.strftime("%Y-%m-%d %H:%M"),0)
          if wait == 1:
               self.bar.SetStatusText(self.Server + " Check Finished with Warning",1)
          else:
               if wait == 2:
                    self.bar.SetStatusText(self.Server + " Check Finished with Errors",1)
               else:
                    if wait == 3:
                         self.bar.SetStatusText(self.Server + " Movie Downloaded with Success",1)
                    else:
                         if wait == 4:
                              self.bar.SetStatusText(self.Server + " Movie Not Downloaded",1)
                         else:
                              self.bar.SetStatusText(self.Server + " Check Finished with success",1)
          self.panel.AutoCheck.Enable()
          
          if wait == 1:
               self.info.ShowMessage(self.messageWarning.GetValue(), wx.ICON_WARNING)
               #------Creation of the Thread to dimiss the InfoBar after 20 secs------
               self.rInfo = RepeatTimer(20,self.StopInfoBar,1)
               self.rInfo.start()
               #------End of Creation of the Thread------
          else:
               if wait == 2:
                    self.info.ShowMessage(self.messageError.GetValue(), wx.ICON_ERROR)
                    #------Creation of the Thread to dimiss the InfoBar after 20 secs------
                    self.rInfo = RepeatTimer(20,self.StopInfoBar,1)
                    self.rInfo.start()
                    #------End of Creation of the Thread------
          

     def StopInfoBar(self):
          self.info.Dismiss()

     def CheckMovieBtnClick(self, evt):
          #self.ag.Play()
          self.panel.AutoCheck.Disable()
          self.panel.CheckMovieBtn.Disable()
          Img = wx.Bitmap("./images/checkinprogress.jpg", wx.BITMAP_TYPE_JPEG)
          self.panel.CheckMovieBtn.SetBitmapLabel(Img)
          #------Opening connection to Histo DB------          
          connHisto = sqlite.connect('./History.db')
          connHisto.row_factory = sqlite.Row
          cHisto = connHisto.cursor()

          cHisto.execute('UPDATE Movie SET New="no"')
          connHisto.commit()
          cHisto.close()
          #------End of Opening connection to Histo DB------
          
          #self.panel.CheckMovieBtn.SetLabel("Please wait...")
          
          if self.panel.server1.GetValue():
               self.Server = "nzbmatrix"
          if self.panel.server2.GetValue():
               self.Server = "nzbs"
          if self.panel.server3.GetValue():
               self.Server = "nzbsu"
          #config.write()
          #------Run of the Thread to check for new movie------          
          if self.Trun : 
               self.lt.run()
          else : 
               self.lt.start()
               self.Trun = 1
          #------End of Run of the Thread to check for new movie------ 
          
     def CheckMovieTimer(self):
          #self.ag.Play()
          self.panel.AutoCheck.Disable()
          self.panel.CheckMovieBtn.Disable()
          Img = wx.Bitmap("./images/checkinprogress.jpg", wx.BITMAP_TYPE_JPEG)
          self.panel.CheckMovieBtn.SetBitmapLabel(Img)
          #------Opening connection to Histo DB------          
          connHisto = sqlite.connect('./History.db')
          connHisto.row_factory = sqlite.Row
          cHisto = connHisto.cursor()

          cHisto.execute('UPDATE Movie SET New="no"')
          connHisto.commit()
          cHisto.close()
          #------End of Opening connection to Histo DB------
          
          if self.panel.server1.GetValue():
               self.Server = "nzbmatrix"
          if self.panel.server2.GetValue():
               self.Server = "nzbs"
          if self.panel.server3.GetValue():
               self.Server = "nzbsu"
               
          #------Run of the Thread to check for new movie------          
          if self.Trun : 
               self.lt.run()
          else : 
               self.lt.start()
               self.Trun = 1
          #------End of Run of the Thread to check for new movie------ 
########################
# IMDB Movie Variables #
########################

def IMDBVarMod(Id):

     try:
          global imdb_json_page
          global imdb_movie_title
          global imdb_movie_year
          global imdb_movie_year_str
          global imdb_movie_description
          global imdb_movie_runtime
          global imdb_movie_runtime_str
          global imdb_movie_rating
          global imdb_movie_rating_str
          global imdb_movie_votes
          global imdb_movie_genres
          global imdb_movie_genres_str
          global imdb_movie_directors
          global imdb_movie_directors_str
          global imdb_movie_cast_members
          global imdb_movie_cast_members_str
          global imdb_movie_image
          global imdb_movie_trailer

          nzbmatrix_imdb_json="http://app.imdb.com/title/maindetails?api=v1&appid=iphone1&locale=en_US&timestamp=1286888328&tconst=" + Id + "&sig=app1"

          class AppURLopener(urllib.FancyURLopener):
               version = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16"
          urllib._urlopener = AppURLopener()

          nzbmatrix_imdb_json_page_request = urllib.urlopen(nzbmatrix_imdb_json).read()

          imdb_json_page = json.loads(nzbmatrix_imdb_json_page_request)
          
          #imdb movie image
        
          try:
               imdb_movie_image = imdb_json_page["data"]["image"]["url"]
          except:
               imdb_movie_image = ""
               
          
          #imdb movie title      
          imdb_json_title = imdb_json_page["data"]["title"]

          imdb_movie_title = decode_htmlentities(imdb_json_title)

          imdb_movie_title = imdb_movie_title.encode("utf-8")

          #remove/replace illegal characters from imdb title (used for nzb filename)
          imdb_movie_title = re.sub("\.","" ,imdb_movie_title)
          imdb_movie_title = re.sub("\:","" ,imdb_movie_title)
          imdb_movie_title = re.sub("\"","" ,imdb_movie_title)
          imdb_movie_title = re.sub("\*","" ,imdb_movie_title)
          imdb_movie_title = re.sub("\"","" ,imdb_movie_title)
          imdb_movie_title = re.sub("/"," " ,imdb_movie_title)
          imdb_movie_title = re.sub("\\\\"," " ,imdb_movie_title)
          imdb_movie_title = re.sub("\?","" ,imdb_movie_title)
          imdb_movie_title = re.sub("\|","" ,imdb_movie_title)
          imdb_movie_title = re.sub("\<","" ,imdb_movie_title)
          imdb_movie_title = re.sub("\>","" ,imdb_movie_title)


          #replace roman numerals to numerics - e.g. "the movie IX" converts to "the movie 9"
          imdb_movie_title = re.sub("(?<![a-zA-Z0-9_])IX(?![a-zA-Z0-9_])","9", imdb_movie_title, re.I)

          #replace roman numerals to numerics - e.g. "the movie VIII" converts to "the movie 8"
          imdb_movie_title = re.sub("(?<![a-zA-Z0-9_])VIII(?![a-zA-Z0-9_])","8", imdb_movie_title, re.I)

          #replace roman numerals to numerics - e.g. "the movie VII" converts to "the movie 7"
          imdb_movie_title = re.sub("(?<![a-zA-Z0-9_])VII(?![a-zA-Z0-9_])","7", imdb_movie_title, re.I)

          #replace roman numerals to numerics - e.g. "the movie VI" converts to "the movie 6"
          imdb_movie_title = re.sub("(?<![a-zA-Z0-9_])VI(?![a-zA-Z0-9_])","6", imdb_movie_title, re.I)

          #replace roman numerals to numerics - e.g. "the movie V" converts to "the movie 5"
          imdb_movie_title = re.sub("(?<![a-zA-Z0-9_])V(?![a-zA-Z0-9_])","5", imdb_movie_title, re.I)

          #replace roman numerals to numerics - e.g. "the movie IV" converts to "the movie 4"
          imdb_movie_title = re.sub("(?<![a-zA-Z0-9_])IV(?![a-zA-Z0-9_])","4", imdb_movie_title, re.I)

          #replace roman numerals to numerics - e.g. "the movie III" converts to "the movie 3"
          imdb_movie_title = re.sub("(?<![a-zA-Z0-9_])III(?![a-zA-Z0-9_])","3" ,imdb_movie_title, re.I)

          #replace roman numerals to numerics - e.g. "the movie II" converts to "the movie 2"
          imdb_movie_title = re.sub("(?<![a-zA-Z0-9_])II(?![a-zA-Z0-9_])","2" ,imdb_movie_title, re.I)

          #converts first letter of each word in the movie title to caps e.g. "the movie" converts to "The Movie"
          imdb_movie_title = string.capwords(imdb_movie_title)

          #imdb movie release date     
          imdb_movie_year = imdb_json_page["data"]["year"]
          imdb_movie_year = int(imdb_movie_year)
          imdb_movie_year_str = str(imdb_movie_year)

          #imdb movie runtime
          try:

               imdb_movie_runtime = imdb_json_page["data"]["runtime"]["time"]
               imdb_movie_runtime = int(imdb_movie_runtime) / 60
               imdb_movie_runtime_str = str(imdb_movie_runtime)

          except:

               imdb_movie_runtime = 1
               imdb_movie_runtime_str = str(imdb_movie_runtime)

          #imdb movie rating
          try:
               imdb_movie_rating = imdb_json_page["data"]["rating"]
               imdb_movie_rating = float(imdb_movie_rating)
               imdb_movie_rating_str = str(imdb_movie_rating)

          except:

               imdb_movie_rating = 1.0
               imdb_movie_rating_str = str(imdb_movie_rating)

          #imdb movie votes
          try:

               imdb_movie_votes = imdb_json_page["data"]["num_votes"]
               imdb_movie_votes = int(imdb_movie_votes)

          except:

               imdb_movie_votes = 1

          #imdb movie director
          try:

               imdb_movie_directors = imdb_json_page["data"]["directors_summary"]
               imdb_movie_directors_str = str(imdb_movie_directors)
               imdb_movie_directors_str = decode_htmlentities(imdb_movie_directors_str)
               imdb_movie_directors_str = imdb_movie_directors_str.encode("utf-8")

          except:

               imdb_movie_directors = "Unknown"
               imdb_movie_directors_str = "Unknown"

          #imdb movie cast
          try:

               imdb_movie_cast_members = imdb_json_page["data"]["cast_summary"]
               imdb_movie_cast_members_str = str(imdb_movie_cast_members)
               imdb_movie_cast_members_str = decode_htmlentities(imdb_movie_cast_members_str)
               imdb_movie_cast_members_str = imdb_movie_cast_members_str.encode("utf-8")

          except:

               imdb_movie_cast_members = "Unknown"
               imdb_movie_cast_members_str = "Unknown"

          #imdb movie description
          try:

               imdb_movie_description = imdb_json_page["data"]["plot"]["outline"]
               imdb_movie_description = decode_htmlentities(imdb_movie_description)
               imdb_movie_description = imdb_movie_description.encode("utf-8")

          except:

               imdb_movie_description = "Unknown"

          #imdb movie genres
          try:

               imdb_movie_genres = imdb_json_page["data"]["genres"]
               imdb_movie_genres_str = str(imdb_movie_genres)

          except:

               imdb_movie_genres = "Unknown"
               imdb_movie_genres_str = "Unknown"
          
          try:

               imdb_movie_trailer = imdb_json_page["data"]["trailer"]["encodings"]["iPhone 3G"]["url"]

          except:

               imdb_movie_trailer = ""

     except:

          return "IMDB API ERROR"

def IMDBVarModPoster(Id):

     try:
          global imdb_json_pagePoster
          global imdb_movie_imagePoster

          nzbmatrix_imdb_json="http://app.imdb.com/title/maindetails?api=v1&appid=iphone1&locale=en_US&timestamp=1286888328&tconst=" + Id + "&sig=app1"

          class AppURLopener(urllib.FancyURLopener):
               version = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16"
          urllib._urlopener = AppURLopener()

          nzbmatrix_imdb_json_page_request = urllib.urlopen(nzbmatrix_imdb_json).read()

          imdb_json_pagePoster = json.loads(nzbmatrix_imdb_json_page_request)
          
          #imdb movie image
        
          try:
               imdb_movie_imagePoster = imdb_json_pagePoster["data"]["image"]["url"]
          except:
               imdb_movie_imagePoster = ""

     except:

          return "IMDB API ERROR"          
     ##########################
     # html entity conversion #
     ##########################

def decode_htmlentities(text):

     def fixup(m):

          text = m.group(0)

          if text[:2] == "&#":

               try:
                                   #hex character reference
                    if text[:3] == "&#x":

                         return unichr(int(text[3:-1], 16))

                    else:

                         return unichr(int(text[2:-1]))

               except ValueError:

                    pass

          else:

               #named character reference
               try:

                    text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])

               except KeyError:

                    pass

          #no match found leave text
          return text

     return re.sub("&#?\w+;", fixup, text)

# RepeatTimer Copyright (c) 2009 Geoffrey Foster
# 
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
class RepeatTimer(Thread):
     def __init__(self, interval, function, iterations=0, args=[], kwargs={}):
          Thread.__init__(self)
          self.interval = interval
          self.function = function
          self.iterations = iterations
          self.args = args
          self.kwargs = kwargs
          self.finished = Event()
 
     def run(self):
          count = 0
          while not self.finished.is_set() and (self.iterations <= 0 or count < self.iterations):
               self.finished.wait(self.interval)
               if not self.finished.is_set():
                    self.function(*self.args, **self.kwargs)
                    count += 1
 
     def cancel(self):
          self.finished.set()
             
class CrazyBrowser(wx.App):
     def OnInit(self):
          fen = MainWindow("Crazy Beaver - Nzb's made easy     " + Version)
          fen.Show(True)
          self.SetTopWindow(fen)
          return True

app = CrazyBrowser()
app.MainLoop()